﻿package com.sxhalo.manage.web.action;

import java.util.*;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sxhalo.manage.map.*;
import com.sxhalo.manage.service.IBaseService;
import com.sxhalo.manage.utils.DateUtil;
import com.sxhalo.manage.utils.Pager;
import com.sxhalo.manage.utils.PasswordEncoder;
import com.sxhalo.manage.web.form.ModulesForm;
import com.sxhalo.manage.web.form.UsersForm;

public class UsersAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private int draw = 1;

	private int start = 0;

	private int length = 20;

	private UsersForm users;

	// 将会被Struts2序列化为JSON字符串的对象
	private Map<String, Object> dataMap;

	private List<UsersForm> dataList;

	// 业务层
	private IBaseService<SysUsers> myService;

	private IBaseService<SysModules> moduleService;

	private IBaseService<SysRoleModules> roleService;

	private IBaseService<SysUserinfo> infoService;

	private IBaseService<Company> companyService;

	private IBaseService<Department> departService;

	private IBaseService<Projects> projectService;

	public int getDraw() {
		return draw;
	}

	public void setDraw(int draw) {
		this.draw = draw;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public UsersForm getUsers() {
		return users;
	}

	public void setUsers(UsersForm users) {
		this.users = users;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public List<UsersForm> getDataList() {
		return dataList;
	}

	public void setDataList(List<UsersForm> dataList) {
		this.dataList = dataList;
	}

	public IBaseService<SysUsers> getMyService() {
		return myService;
	}

	public void setMyService(IBaseService<SysUsers> myService) {
		this.myService = myService;
	}

	public IBaseService<SysModules> getModuleService() {
		return moduleService;
	}

	public void setModuleService(IBaseService<SysModules> moduleService) {
		this.moduleService = moduleService;
	}

	public IBaseService<SysRoleModules> getRoleService() {
		return roleService;
	}

	public void setRoleService(IBaseService<SysRoleModules> roleService) {
		this.roleService = roleService;
	}

	public IBaseService<SysUserinfo> getInfoService() {
		return infoService;
	}

	public void setInfoService(IBaseService<SysUserinfo> infoService) {
		this.infoService = infoService;
	}

	public IBaseService<Company> getCompanyService() {
		return companyService;
	}

	public void setCompanyService(IBaseService<Company> companyService) {
		this.companyService = companyService;
	}

	public IBaseService<Department> getDepartService() {
		return departService;
	}

	public void setDepartService(IBaseService<Department> departService) {
		this.departService = departService;
	}

	public IBaseService<Projects> getProjectService() {
		return projectService;
	}

	public void setProjectService(IBaseService<Projects> projectService) {
		this.projectService = projectService;
	}

	/**
	 * 构造方法
	 */
	public UsersAction() {
		// 初始化Map对象
		dataMap = new HashMap<String, Object>();
	}

	public String validUserName() {
		dataMap.clear();
		try {
			SysUsers entity = myService.find("userUsername",
					users.getUserUsername());
			if (entity == null) {
				dataMap.put("valid", true);
			} else {
				if (users.getUserId().equals(entity.getUserId())) {
					dataMap.put("valid", true);
				} else {
					dataMap.put("valid", false);
				}
			}
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	public String getCurrentUser() {
		dataMap.clear();
		try {
			String userName = ServletActionContext.getRequest().getRemoteUser();
			SysUsers entity = myService.find("userUsername", userName);
			ActionContext.getContext().getSession().put("user", entity);
			dataMap.put("user", userName);
			dataMap.put("menu", getUserModules(entity));
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String getEntity() {
		
		SysUsers entity = myService.findById(users.getUserId());
		BeanUtils.copyProperties(entity, users);
		SysUserinfo info = entity.getSysUserinfo();
		users.setUserinfoTruename(info.getUserinfoTruename());
		users.setUserinfoPosition(info.getUserinfoPosition());
		users.setUserinfoAddress(info.getUserinfoAddress());
		users.setUserinfoAddress2(info.getUserinfoAddress2());
		users.setUserinfoPhone(info.getUserinfoPhone());
		users.setUserinfoPhone2(info.getUserinfoPhone2());
		users.setUserinfoEmail(info.getUserinfoEmail());
		users.setUserinfoEmail2(info.getUserinfoEmail2());
		users.setUserinfoZip(info.getUserinfoZip());
		users.setUserinfoFax(info.getUserinfoFax());
		users.setUserinfoRemark(info.getUserinfoRemark());
		users.setUserinfoState(info.getUserinfoState());
		users.setUserinfoOrder(info.getUserinfoOrder());
		Company company = entity.getSysUserinfo().getCompany();
		users.setUserinfoCompany(company.getCompanyId());
		Department department = entity.getSysUserinfo().getDepartment();
		users.setUserinfoDepartment(department.getDepartmentId());
		// 返回结果
		return SUCCESS;
	}
	
	public String getForm() {
		List<Company> clist = companyService.findAll();
		List<Department> dlist = departService.findList("companyId",
				clist.get(0).getCompanyId());
		try {
			SysUsers entity = myService.findById(users.getUserId());
			BeanUtils.copyProperties(entity, users);
			SysUserinfo info = entity.getSysUserinfo();
			users.setUserinfoTruename(info.getUserinfoTruename());
			users.setUserinfoPosition(info.getUserinfoPosition());
			users.setUserinfoAddress(info.getUserinfoAddress());
			users.setUserinfoAddress2(info.getUserinfoAddress2());
			users.setUserinfoPhone(info.getUserinfoPhone());
			users.setUserinfoPhone2(info.getUserinfoPhone2());
			users.setUserinfoEmail(info.getUserinfoEmail());
			users.setUserinfoEmail2(info.getUserinfoEmail2());
			users.setUserinfoZip(info.getUserinfoZip());
			users.setUserinfoFax(info.getUserinfoFax());
			users.setUserinfoRemark(info.getUserinfoRemark());
			users.setUserinfoState(info.getUserinfoState());
			users.setUserinfoOrder(info.getUserinfoOrder());
			Company company = entity.getSysUserinfo().getCompany();
			users.setUserinfoCompany(company.getCompanyId());
			Department department = entity.getSysUserinfo().getDepartment();
			users.setUserinfoDepartment(department.getDepartmentId());
			if (info.getUserinfoBirthday() != null) {
				users.setUserBirthday(DateUtil.formatShort(info
						.getUserinfoBirthday()));
			}
			// 部门取值
			dlist = departService.findList("companyId", company.getCompanyId());
		} catch (Exception re) {

		}
		ActionContext.getContext().put("clist", clist);
		ActionContext.getContext().put("dlist", dlist);
		// 返回结果
		return SUCCESS;
	}

	public String getGridData() {
		// dataMap中的数据将会被Struts2转换成JSON字符串，所以这里要先清空其中的数据
		dataMap.clear();
		// 获取数据
		try {
			int page = start == 0 ? 1 : start / length + 1;
			int size = length < 0 ? Integer.MAX_VALUE : length;
			Pager<SysUsers> list = myService.findPagerList(page, size, "", "");
			dataMap.put("draw", draw);
			dataMap.put("recordsTotal", list.getTotal());
			dataMap.put("recordsFiltered", list.getTotal());
			dataMap.put("data", copyList(list.getList()));
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String getCompanyUser() {
		// 获取数据
		try {
			String proid = ServletActionContext.getRequest().getParameter(
					"proid");
			String cid = ServletActionContext.getRequest().getParameter("cid");
			if (proid != null) {
				cid = projectService.findById(proid).getCompany()
						.getCompanyId().toString();
			}
			List<UsersForm> data = new ArrayList<UsersForm>();
			List<SysUsers> list = myService.findAll();
			for (SysUsers po : list) {
				String comid = po.getSysUserinfo().getCompany().getCompanyId()
						.toString();
				if (comid.equals(cid)) {
					UsersForm vo = new UsersForm();
					BeanUtils.copyProperties(po, vo);
					BeanUtils.copyProperties(po.getSysUserinfo(), vo);
					data.add(vo);
				}
			}
			dataList = data;
		} catch (Exception re) {

		}
		// 返回结果
		return SUCCESS;
	}

	public String addEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		try {
			SysUsers entity = new SysUsers();
			BeanUtils.copyProperties(users, entity);
			SysUserinfo info = new SysUserinfo();
			BeanUtils.copyProperties(users, info);
			Company company = new Company();
			company.setCompanyId(users.getUserinfoCompany());
			info.setCompany(company);
			Department department = new Department();
			department.setDepartmentId(users.getUserinfoDepartment());
			info.setDepartment(department);
			if (!users.getUserBirthday().equals("")) {
				info.setUserinfoBirthday(DateUtil.parseShort(users
						.getUserBirthday()));
			}

			String userName = ServletActionContext.getRequest().getRemoteUser();
			SysUsers currUser = myService.find("userUsername", userName);
			entity.setUserPassword(PasswordEncoder.MD5(users.getUserPassword()));
			entity.setSysUserinfo(info);
			entity.setUserParent(currUser.getUserId());
			entity.setUserIsdisable(1);
			infoService.save(info);
			myService.save(entity);
			dataMap.put("valid", true);
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	public String editEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		try {
			SysUsers entity = myService.findById(users.getUserId());
			entity.setUserUsername(users.getUserUsername());
			SysUserinfo info = entity.getSysUserinfo();
			BeanUtils.copyProperties(users, info);
			Company company = new Company();
			company.setCompanyId(users.getUserinfoCompany());
			info.setCompany(company);
			Department department = new Department();
			department.setDepartmentId(users.getUserinfoDepartment());
			info.setDepartment(department);
			if (!users.getUserBirthday().equals("")) {
				info.setUserinfoBirthday(DateUtil.parseShort(users
						.getUserBirthday()));
			}
			myService.update(entity);
			dataMap.put("valid", true);
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	public String checkPassword() {
		dataMap.clear();
		try {
			String userName = ServletActionContext.getRequest().getRemoteUser();
			SysUsers entity = myService.find("userUsername", userName);
			if (entity != null) {
				String oldPassword = PasswordEncoder
						.MD5(users.getOldPassword());
				if (entity.getUserPassword().equals(oldPassword)) {
					dataMap.put("valid", true);
				} else {
					dataMap.put("valid", false);
				}
			} else {
				dataMap.put("valid", false);
			}
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	public String updatePassword() {
		try {
			String userName = ServletActionContext.getRequest().getRemoteUser();
			SysUsers entity = myService.find("userUsername", userName);
			if (entity != null) {
				String oldPassword = PasswordEncoder
						.MD5(users.getOldPassword());
				if (entity.getUserPassword().equals(oldPassword)) {
					entity.setUserPassword(PasswordEncoder.MD5(users
							.getUserPassword()));
					myService.update(entity);
					dataMap.put("valid", true);
				} else {
					dataMap.put("valid", false);
				}
			} else {
				dataMap.put("valid", false);
			}
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	public String delEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		try {
			SysUsers entity = myService.findById(users.getUserId());
			if (myService.delete(entity)) {
				dataMap.put("valid", true);
			} else {
				dataMap.put("valid", false);
			}
		} catch (Exception re) {
			dataMap.put("valid", false);
		}
		// 返回结果
		return SUCCESS;
	}

	private List<UsersForm> copyList(List<SysUsers> list){
		List<UsersForm> data = new ArrayList<UsersForm>();
		for (SysUsers po : list) {
			UsersForm vo = new UsersForm();
			BeanUtils.copyProperties(po, vo);
			BeanUtils.copyProperties(po.getSysUserinfo(), vo);
			vo.setUserinfoCompanyName(po.getSysUserinfo().getCompany().getCompanyName());
			vo.setUserinfoDepartmentName(po.getSysUserinfo().getDepartment().getDepartmentName());
			data.add(vo);
		}
		return data;
	}
	
	private List<ModulesForm> getUserModules(SysUsers user) {
		List<SysModules> data = null;
		if (user.getUserUsername().equals("admin")) {
			data = moduleService.findAll();
		} else {
			Set<SysRoles> roles = user.getSysRoleses();
			Set<SysModules> modules = new HashSet<SysModules>(0);
			for (SysRoles ro : roles) {
				List<SysRoleModules> roleModule = roleService.findList(
						"sysRoles", ro);
				for (SysRoleModules rm : roleModule) {
					modules.add(rm.getSysModules());
				}
			}
			data = new ArrayList<SysModules>(modules);
		}
		return getChildren(0, data);
	}

	private List<ModulesForm> getChildren(Integer pId, List<SysModules> source) {
		List<ModulesForm> data = new ArrayList<ModulesForm>();
		Collections.sort(source, new Comparator<SysModules>() {
			public int compare(SysModules arg0, SysModules arg1) {
				return arg0.getModuleSort().compareTo(arg1.getModuleSort());
			}
		});
		for (SysModules po : source) {
			if (po.getModuleParent() == pId) {
				ModulesForm vo = new ModulesForm();
				BeanUtils.copyProperties(po, vo);
				vo.setChildren(getChildren(po.getModuleId(), source));
				data.add(vo);
			}
		}
		return data;
	}
}
